const Controller = require('egg').Controller;

class RestController extends Controller {
    constructor(props) {
        super(props);
        this.table = '';
    }
    async create() {
        const ctx = this.ctx;
        const request = this.ctx.params;
        const queries = this.ctx.request.body;
        const { mysql } = this.app;
        console.log(queries)
        const data = await mysql.insert(this.table, queries);
        ctx.body = {
            status: 0,
            message: data,
        };
        ctx.status = 200;
    }
    async index() {
        const ctx = this.ctx, request = this.ctx.params,
            queries = this.ctx.queries,
            { mysql } = this.app,
            limit = queries.limit || 20,
            offset = queries.offset || 0,
            orders = queries.orders,
            hasLimit = !!queries.limit,
            columns = queries.columns;
        delete queries.limit;
        delete queries.offset;
        delete queries.orders;
        delete queries.columns;

        Object.keys(queries).forEach(v => { if (!queries[v]) delete queries[v] })

        const data = await mysql.select(this.table, Object.assign({
            where: queries,
            limit, // 返回数据量
            offset, // 数据偏移量
        },
            columns ? { columns: JSON.parse(columns) } : {},
            orders ? { orders: JSON.parse(orders) } : {}
        ));
        if (hasLimit) {
            const count = await mysql.count(this.table, queries)
            ctx.body = {
                status: 0,
                message: { data: data, count: count },
            };
            ctx.status = 200;
        } else {
            ctx.body = {
                status: 0,
                message: data,
            };
            ctx.status = 200;
        }
    }
    async new() {

    }
    async show() {

    }
    async edit() {

    }
    async update() {
        const ctx = this.ctx;
        const id = this.ctx.params.id;
        const queries = this.ctx.request.body;
        queries.id = id;
        const { mysql } = this.app;
        const data = await mysql.update(this.table, queries);
        ctx.body = {
            status: 0,
            message: data,
        };
        ctx.status = 200;
    }
    async destroy() {

    }
    
}
module.exports = RestController;
